<?php

namespace App\Services;

use App\Models\Report;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class ReportService
{
    /**
     * 创建举报
     *
     * @param  User  $user  举报者
     * @param  Model  $reportable  被举报的对象（帖子、回复等）
     * @param  array  $data  举报数据
     */
    public function createReport(User $user, Model $reportable, array $data): Report
    {
        return DB::transaction(function () use ($user, $reportable, $data) {
            // 检查是否已经举报过（同一用户对同一对象只能举报一次）
            $existingReport = Report::where('user_id', $user->id)
                ->where('reportable_type', get_class($reportable))
                ->where('reportable_id', $reportable->id)
                ->first();

            if ($existingReport) {
                throw new \Exception('您已经举报过此内容');
            }

            return Report::create([
                'user_id' => $user->id,
                'reportable_type' => get_class($reportable),
                'reportable_id' => $reportable->id,
                'reason' => $data['reason'],
                'description' => $data['description'] ?? null,
                'status' => 'pending',
            ]);
        });
    }

    /**
     * 获取举报列表（管理员用）
     *
     * @param  string|null  $status  状态筛选
     * @param  int  $perPage  每页数量
     * @return \Illuminate\Pagination\LengthAwarePaginator
     */
    public function getReportsList(?string $status = null, int $perPage = 20)
    {
        $query = Report::with(['user', 'admin', 'reportable']);

        if ($status) {
            $query->where('status', $status);
        }

        return $query->orderBy('created_at', 'desc')->paginate($perPage);
    }

    /**
     * 获取举报详情
     */
    public function getReportDetail(Report $report): Report
    {
        return $report->load(['user', 'admin', 'reportable']);
    }
}
